<?php

/*
 * JSON functionality not present in 5.1.6
 */

if (!function_exists('json_decode')) {
    
	require_once '3rd_party/JSON/JSON.php';
	
	// options will be ignored
    function json_encode($content, $options=null) {
        $json = new Services_JSON;
        return $json->encode($content);
    }
	
	global $last_json_error;
	$last_json_error = false;	
	
    function json_decode($content, $assoc=false) {
		
    	global $last_json_error;
		
        if ($assoc) {
            $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
        }
        else {
            $json = new Services_JSON;
        }
        
        $result = $json->decode($content);
        $last_json_error = $result === null;
        
        return $result;
    }
    
	define('JSON_ERROR_NONE', 'JSON_ERROR_NONE');
	define('JSON_ERROR', 'JSON_ERROR');
    function json_last_error() {
    	
		global $last_json_error;
	
        return $last_json_error? JSON_ERROR : JSON_ERROR_NONE;
    }
}

if (!defined('JSON_PRETTY_PRINT')) {
	define('JSON_PRETTY_PRINT', 0);
}


/*
 * Required date functionality not present in 5.1.6
 */

date_default_timezone_set('Europe/Amsterdam');

require_once '3rd_party/Date-1.5.0a1/Date.php';

/**
 * Converts dd/mm/yyyy string to Date object
 */
function slash_date_string_to_date($slash_date_string) {
	$exploded = explode('/', trim($slash_date_string));
	if (count($exploded) !== 3) {
		throw new Exception('Invalid date');
	}
	$date = new Date();
	$date->setDayMonthYear($exploded[0], $exploded[1], $exploded[2]);
	return $date;
}

function date_to_slash_date_string($date) {
	return $date->format('%d/%m/%Y');
}


/*
 * error_get_last not present in 5.1.6
 */

if( !function_exists('error_get_last') ) {
	set_error_handler(
	create_function(
	            '$errno,$errstr,$errfile,$errline,$errcontext',
	            '
	                global $__error_get_last_retval__;
	                $__error_get_last_retval__ = array(
	                    \'type\'        => $errno,
	                    \'message\'     => $errstr,
	                    \'file\'        => $errfile,
	                    \'line\'        => $errline
	                );
	                return false;
	            '
	)
	);
	function error_get_last() {
		global $__error_get_last_retval__;
		if( !isset($__error_get_last_retval__) ) {
			return null;
		}
		return $__error_get_last_retval__;
	}
}